﻿
local deal_probe_data = function(each_probe, file_path, count)
{
    local file = file_path..count..".csv";

    local rows = each_probe.time_record.size(0);
    local field_data = zeros(rows, 4);

    field_data[:,0] = each_probe.time_record;

    for(k,v in each_probe.datas)
    {
        if(k<3)
        {
            field_data[:, k+1] = v; 
        }
    }

    local first_row = ["# comac datafile version 1.0", "", "",""];
    local second_row = ["# time||ns||key", "mag(Ex)||V/m||value", "mag(Ey)||V/m||value", "mag(Ez)||V/m||value"];

    local field_data_header = cat(0, first_row, second_row);
    field_data = cat(0, field_data_header, field_data);

    io.save_csv(file, field_data);
};

local deal_plane_data = function(each_plane, file_path, count)
{
    local file = file_path..count..".csv";

    local rows = each_plane["Ex"]["data"][0].size(0) * each_plane["Ex"]["data"][0].size(1);

    local field_data = zeros(rows, 5);
    
    local coord_data = [];
    local origin_rows = each_plane["Ex"]["data"][0].size(0);
    local origin_columns = each_plane["Ex"]["data"][0].size(1);
    local row_index = 0;
    for(k,v in 0:origin_rows-1)
    {
        local temp_row = zeros(5);

        for(k1,v1 in 0:origin_columns-1)
        {
            temp_row[0] = each_plane.Ex.coord.x[k];
            temp_row[1] = each_plane.Ex.coord.y[k1];
            temp_row[2] = each_plane.Ex.data[0][k,k1];
            temp_row[3] = each_plane.Ey.data[0][k,k1];
            temp_row[4] = each_plane.Ez.data[0][k,k1];    
        }
        field_data[row_index, :] = temp_row;
        row_index++; 
    }
}



local header_file_path = fs.makepath("header.json", probe_path);
local header = table();
header.datafile_type = "csv";
header.unit = table
{
    coordinate : util.ulname(dparam.UL);
    E_field    : "V/m";
    H_field    : "A/m";
    frequency  : util.ufname(dparam.UF);
    time : util.utname(dparam.UT)
};
header.Domain_info = "Time-domain";
header.field_monitor_type = "point";
header.field_monitor_sample_info = [];
header.field_monitor_name = [];